/**
 * 
 */
package com.hw.hcit.feature;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.storage.DiskInfo;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
/**
 * @author gaoshengpan
 *
 */
public class UsbOtgTestItem extends JTestItem {
   private TextView tvView1;
   private StorageManager mStorageManager = null;
   private Context mContext;
   private StorageEventListener mListener;
   private String TAG = "UsbOtgTestItem";
   private Button mButton1, mButton2;
   private int mReadCount;
   private Boolean detected;
   private static final byte[] OTG_ON = { '1' };
   private static final byte[] OTG_OFF = { '0' };

   /**
    * @param cb
    */
   public UsbOtgTestItem(JCtrlCallback cb) {
      super(cb);
      // TODO Auto-generated constructor stub
   }

   /**
     * 
     */
   public UsbOtgTestItem() {
      // TODO Auto-generated constructor stub
   }

   @Override
   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      mContext = Config.GetActivity().getApplicationContext();

   }

   @Override
   public View onCreateView(android.view.LayoutInflater inflater,
         android.view.ViewGroup container, Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      View rootView = inflater.inflate(R.layout.usbotatest, container, false);
      Log.d(TAG, "mListener" + "notNull111");
      mStorageManager = mContext.getSystemService(StorageManager.class);
      mListener = new StorageEventListener() {
         @Override
         public void onVolumeStateChanged(VolumeInfo vol, int oldState,
               int newState) {

         }

         @Override
         public void onDiskScanned(DiskInfo disk, int volumeCount) {
            String dLable = disk.label;
            String description = disk.getDescription();
            Log.d(TAG, "dLable" + dLable + "\n" + description);
            if (description != null && !"".equals(description)) {
               detected = true;
               mHandler.sendEmptyMessage(2);
               mHandler.removeMessages(0);
               mHandler.removeMessages(1);
            }
         }
      };
      if (mListener != null) {
         Log.d(TAG, "mListener" + "notNull");
      }

      tvView1 = (TextView) rootView.findViewById(R.id.textView1);
      mButton1 = (Button) rootView.findViewById(R.id.button1);
      mButton2 = (Button) rootView.findViewById(R.id.button2);
      mButton1.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (Config.CURR_PROJECT.isAuto()) {
               if (!Config.ageingTested) {
                  rewriteOneByteOfNv2499(21, 'P');
               } else {
                  rewriteOneByteOfNv2499(52, 'P');
               }
            }
            testFinish(true, 1, true);
         }
      });
      mButton2.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (Config.CURR_PROJECT.isAuto()) {
               if (!Config.ageingTested) {
                  rewriteOneByteOfNv2499(21, 'F');
               } else {
                  rewriteOneByteOfNv2499(52, 'F');
               }
            }
            testFinish(false, 1, false);

         }
      });
      // tvView2 = (TextView)rootView.findViewById(R.id.textView2);
      return rootView;
   }

   @Override
   public void onResume() {
      // TODO Auto-generated method stub
      super.onResume();
      /*SystemProperties.set("persist.chg.otg_en", "1");
      SystemProperties.set("debug.lsc_mgr.type", "1");
      setOTGStatus(true);*/
      detected = false;
      mStorageManager.registerListener(mListener);
      List<DiskInfo> disks = mStorageManager.getDisks();
      if (disks != null) {
         for (DiskInfo disk : disks) {
            String description = disk.getDescription();
            if (description != null && !"".equals(description)) {
               detected = true;
            }
         }
      }
      mButton1.setEnabled(false);
      mButton2.setEnabled(false);
      mReadCount = 0;
      mHandler.sendEmptyMessageDelayed(0, 1000);
   }

   private void setOTGStatus(boolean status) {
	      FileOutputStream red;
	     
	      try {
	         byte[] ledData = OTG_OFF;
	         ledData = status ? OTG_ON : OTG_OFF;
	         red = new FileOutputStream(
	               "/proc/mtk_battery_cmd/otg_en_cmd");
	         red.write(ledData);
	         red.close();
	      } catch (IOException e) {
	         e.printStackTrace();
	      }
	   }
   private Handler mHandler = new Handler() {

      @Override
      public void handleMessage(Message msg) {
         // TODO Auto-generated method stub
         super.handleMessage(msg);
         switch (msg.what) {
         case 0:
            if (detected) {
               mButton1.setEnabled(true);
               tvView1.setText(getString(R.string.test_success));
               Log.d(TAG, "case 0:" + "OK");
            } else {
               mHandler.sendEmptyMessageDelayed(1, 1000);
            }

            break;
         case 1:
            mReadCount++;
            Log.d(TAG, "mReadCount++:" + mReadCount);
            if (mReadCount == 4) {
               if (detected) {
                  mButton1.setEnabled(true);
                  tvView1.setText(getString(R.string.test_success));
                  Log.d(TAG, "case 1:3" + "OK");
               } else {
                  mButton2.setEnabled(true);
                  tvView1.setText(getString(R.string.test_fail));
                  Log.d(TAG, "case 1:3" + "fail");
               }
               if (mHandler.hasMessages(1)) {
                  mHandler.removeMessages(1);
               }
            }
            if (mReadCount < 4) {
               if (detected) {
                  mButton1.setEnabled(true);
                  tvView1.setText(getString(R.string.test_success));
                  Log.d(TAG, "case 1:" + "OK");

               } else {
                  mHandler.sendEmptyMessageDelayed(1, 1000);
               }
            }

            break;
         case 2:
                mButton1.setEnabled(true);
                tvView1.setText(getString(R.string.test_success));
                Log.d(TAG, "case 3:" + "OK");
              break;

         default:
            break;
         }

      }
   };
   

   @Override
   public boolean dispatchKeyEvent(KeyEvent event) {
      // TODO Auto-generated method stub
      return true;
   }

   /* gaoshenpan 15-08-31 close OTG charge begin */
   @Override
   public void onPause() {
      // TODO Auto-generated method stub
      super.onPause();
      Log.d(TAG, "onPause++:" + "remove");
 /*     SystemProperties.set("persist.chg.otg_en", "0");
      SystemProperties.set("debug.lsc_mgr.type", "0");
      setOTGStatus(false);*/
      mStorageManager.unregisterListener(mListener);
      mHandler.removeMessages(0);
      mHandler.removeMessages(1);

   }

   /* gaoshenpan 15-08-31 close OTG charge end */

   private String readFile(String filePath) {
      String res = "";
      try {
         BufferedReader br = new BufferedReader(new InputStreamReader(
               new FileInputStream(new File(filePath))));
         String str = null;
         while ((str = br.readLine()) != null) {
            res += str;
         }
         if (br != null) {
            br.close();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return res;
   }

   /* 15-09-02 gaoshenpan fix can not find source when onDetach begin */
   @Override
   public void onDetach() {
      // TODO Auto-generated method stub
      super.onDetach();
      mHandler.removeMessages(1);
   }
   /* 15-09-02 gaoshenpan fix can not find source when onDetach end */
}

